package com.backend.vse.ws;

import com.alibaba.fastjson.JSON;
import com.backend.vse.common.Result;
import com.backend.vse.entity.User;
import com.backend.vse.interceptor.JwtInterceptor;
import com.backend.vse.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/exp8")
public class wsController1 {
    private static WsUser user = new WsUser();
    @Autowired
    private UserService userService;

    @GetMapping("/matchUser1")
    public Result matchUser(String index, String role) {
        List<String> userIds = JwtInterceptor.getUserIds();
        if (userIds != null && !userIds.isEmpty()) {
            List<String> list = userIds.stream().filter(i -> !i.equals(index)).toList();
            if (!list.isEmpty()) {
                User suser = userService.findUserByIndex(Long.valueOf(index));
                User user = userService.findUserByIndex(Long.valueOf(list.get(0)));

                WsUser data = new WsUser()
                        .setSource(role)
                        .setSourceName(suser.getName())
                        .setTarget(role.equals("买方") ? "卖方" : "买方")
                        .setSourceId(index).setTargetId(list.get(0))
                        .setTargetName(user.getName());
                Map<String, Object> map = new HashMap<>();
                map.put("event", "MATCH!");
                map.put("data", data);
                WsServerHandler.sendMessage(JSON.toJSONString(map));
                return Result.success(data);
            }
        }
        return Result.fail(500, "没有匹配到在线对手");
    }

    @GetMapping("/begin1")
    public Result begin(@RequestBody WsUser data) {
        log.info("开始实验, {}", data);
        if (user.getSourceId() != null) {
            return Result.fail(500, "已经有用户在实验中");
        }
        user = data;
        return Result.success(data);
    }

}
